import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class Leetcode145 {
//    public List<Integer> postorderTraversal(TreeNode root) {
//        List<Integer> list = new ArrayList<>();
//        dfs(root,list);
//        return list;
//    }
//    public void dfs(TreeNode root,List<Integer> list){
//        if (root==null){
//            return;
//        }
//        dfs(root.left,list);
//        dfs(root.right,list);
//        list.add(root.val);
//    }
public List<Integer> postorderTraversal(TreeNode root){
    Stack<TreeNode> stack = new Stack<>();
    ArrayList<Integer> result = new ArrayList<>();
    if (root!=null) stack.push(root);
    while (!stack.isEmpty()){
        TreeNode peek = stack.peek();
        if (peek!=null){
            stack.pop();
            stack.push(peek);
            stack.push(null);
            if (peek.right!=null) stack.push(peek.right);
            if (peek.left!=null) stack.push(peek.left);
        }else {
            stack.pop();
            TreeNode pop = stack.pop();
            result.add(pop.val);
        }
    }
    return result;
}
}
